
import axios from 'axios';
// import { useNavigate } from 'react-router-dom';
// const navigate=useNavigate()
interface Obj {
  id: string,
  title:string,
  path:string,
  icon:string,
  parentId:string
}
// interface Obj2{
//   _id:string,
//   name:string,
//   password:string,
//   role_id:string,
//   lastLogin:string,
//   status:number
// }
// 1. 定义响应数据的通用接口
export interface ApiResponse<T = any> {
  code: number;
  token?: string;
  menu?: any[];
  user?: any;
  data?: T;
  message?: string;
}

// 2. 创建 axios 实例
const service = axios.create({
  baseURL: 'http://localhost:3000', // 你的后端接口前缀
  timeout: 10000,
  withCredentials: false,
})as any

// 3. 请求拦截器（可选，按需加 token）
service.interceptors.request.use(
  (config: any) => {
    // 例如：登录接口不加 token
    if (
      config.url?.includes('/login') 
    ) {
      return config;
    }
    const token = localStorage.getItem('token');
    if (token && config.headers) {
      config.headers.Authorization = 'Bearer ' + token;
    } else {

      alert('请先登录')
      window.location.href = '/login'; 
      return Promise.reject(new Error('Token missing'));
    }
    return config;
  },
  (error: any) => Promise.reject(error)
);

// 4. 响应拦截器 —— 只返回 data 字段
service.interceptors.response.use(
  (response: any) => response.data, // 只返回 data
  (error:any) => {
    const status = error?.response?.status;
    const code = error?.response?.data?.code;
    if (status === 401 || code === 401) {
      alert('登录已过期，请重新登录');
      localStorage.removeItem('token');
      window.location.href = '/login'; 
    }
    return Promise.reject(error);
  }
);

// 5. 通用请求方法，直接返回业务数据
export function request<T = any>(config: any): Promise<ApiResponse<T>> {
  return service(config) as Promise<ApiResponse<T>>;
}

export default service;